var util = require('../../../utils/util.js');
var api = require('../../../config/api.js');
var user = require('../../../services/user.js');
var app = getApp();

Page({
  data: {
    userInfo: {}
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    this.setData({
      userInfo: app.globalData.userInfo
    })
  },
  onReady: function () {

  },
  onShow: function () {

    let userInfo = wx.getStorageSync('userInfo');
    let token = wx.getStorageSync('token');

    // 页面显示
    if (userInfo && token) {
      app.globalData.userInfo = userInfo;
      app.globalData.token = token;
    }

    this.setData({
      userInfo: app.globalData.userInfo,
    });

  },
  onHide: function () {
    // 页面隐藏

  },
  onUnload: function () {
    // 页面关闭
  },
  bindGetUserInfo: function (e) {
    if (e.detail.userInfo) {
      //用户按了允许授权按钮
      wx.getSetting({
        success: res => {
          console.log(res);
          if (res.authSetting['scope.userInfo']) {
            // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
            wx.getUserInfo({
              success: res => {
                app.globalData.userInfo = res.userInfo;
                this.setData({
                  userInfo: app.globalData.userInfo,
                });
                if (this.userInfoReadyCallback) {
                  this.userInfoReadyCallback(res)
                }
                wx.login({
                  success: function (res2) {
                    let body = {
                      code: res2.code,
                      // userInfo: res.userInfo
                      nickName: res.userInfo.nickName,
                      avatarUrl: res.userInfo.avatarUrl
                    }
                    util.request(api.loginUrl, body, "GET")
                      .then(function (res) {
                        util.session = res;
                      })
                  }
                });
              }
            })
          }
        }
      })
      // wx.switchTab({
      //   url: '/pages/index/index',
      // });
    } else {
      //用户按了拒绝按钮
    }
  },
  exitLogin: function () {
    wx.showModal({
      title: '',
      confirmColor: '#b4282d',
      content: '退出登录？',
      success: function (res) {
        if (res.confirm) {
          wx.removeStorageSync('token');
          wx.removeStorageSync('userInfo');
          wx.switchTab({
            url: '/pages/index/index'
          });
        }
      }
    })

  }
})